from django.shortcuts import render, get_object_or_404
from .models import Event, BanEvent
from django.http import HttpResponse, HttpResponseRedirect
from django.urls import reverse
from .forms import EditorForm, BanForm
from django.contrib.auth.decorators import login_required
from . import func
import mistune
import datetime
import pytz

# Create your views here.

def index(request):
	sort_events = Event.objects.order_by("date")
	all_events = []
	for event in sort_events:
		if not event.ban:
			all_events.append(event)
		else:
			if datetime.datetime.now().replace(tzinfo=pytz.timezone('Asia/Shanghai')) > event.end_ban:
				event.ban = False
				all_events.append(event)

	context = {"sort_events": all_events}
	return render(request, "events/index.html", context=context)

def look(request, event_id):
	look_event = get_object_or_404(Event, event_id=event_id)
	if look_event.ban == True:
		if datetime.datetime.now().replace(tzinfo=pytz.timezone('Asia/Shanghai')) > look_event.end_ban:
			look_event.ban = False
		else:
			return HttpResponseRedirect(reverse('events:index'))

	context = {"look_event":look_event}
	render_md = mistune.create_markdown(plugins=['strikethrough', 'table'])
	markdown_html = render_md(look_event.spe_event)
	markdown_html = func.filler_replace(markdown_html)	
	context['markdown'] = markdown_html
	return render(request, "events/look.html", context=context)

@login_required
def editor(request, event_id):
	if request.method == 'POST':
		editor_event = get_object_or_404(Event, event_id=event_id)
		if request.POST['title'] == '' or request.POST['spe_event'] == '' or request.POST['date'] == None:
			return render(request, "events/errot_null.html")

		editor_event.title = request.POST['title']
		editor_event.spe_event = request.POST['spe_event']
		editor_event.date = request.POST['date']
		editor_event.spe_event = request.POST['spe_event']
		editor_event.last_edit_name = request.user.username
		editor_event.save()

		return HttpResponseRedirect(reverse("events:look", kwargs={"event_id":event_id}))
	else:
		editor_event = get_object_or_404(Event, event_id=event_id)
		editor_form = EditorForm()
		editor_form.fields['spe_event'].initial = editor_event.spe_event
		editor_form.fields['date'].initial = editor_event.date
		editor_form.fields['title'].initial = editor_event.title
		context = {"editor_event":editor_event, 'editor_form':editor_form}
		return render(request, "events/editor.html", context=context)

@login_required
def create(request):
	if request.method == 'POST':
		new_event = Event()
		if request.POST['title'] == None or request.POST['spe_event'] == None or request.POST['date'] == None:
			return render(request, "events/errot_null.html")

		all_events = Event.objects.all()
		count = 0
		for i in all_events:
			count += 1

		new_event.event_id = count + 1
		new_event.date = request.POST['date']
		new_event.title = request.POST['title']
		new_event.spe_event = request.POST['spe_event']
		new_event.last_edit_name = request.user.username

		new_event.save()

		return HttpResponseRedirect(reverse("events:look", kwargs={"event_id":new_event.event_id}))
	else:
		editor_form = EditorForm()
		context = {'editor_form':editor_form}
		return render(request, "events/create.html", context=context)

@login_required
def exchange_ban(request, event_id):
	if request.method == 'POST':
		ban_form = BanForm()
		code = request.POST['code']
		if not BanEvent.objects.filter(code=code):
			return render(request, 'events/exchange_ban.html', context={'ban_form': ban_form, 
					'event_id': event_id, 'errmsg': '邀请码不存在'})
		if get_object_or_404(BanEvent, code=code).number_for_times <= 0:
			return render(request, 'events/exchange_ban.html', context={'ban_form': ban_form, 
					'event_id': event_id, 'errmsg': '邀请码已失效'})

		ban_event = get_object_or_404(BanEvent, code=code)
		ban_event.number_for_times -= 1
		ban_event.save()

		event = get_object_or_404(Event, event_id=event_id)
		event.ban = True
		event.end_ban = datetime.datetime.now().replace(tzinfo=pytz.timezone('Asia/Shanghai')) \
					+ datetime.timedelta(days=30)
		event.save()

		return HttpResponseRedirect(reverse("events:index"))
	else:
		ban_form = BanForm()
		context = {'ban_form': ban_form, 'event_id': event_id}
		return render(request, 'events/exchange_ban.html', context=context)
